﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dx.Common
{
    /// <summary>
    /// 日志服务
    /// </summary>
    public class LogHelper
    {
        public static readonly LogHelper Instance = new LogHelper();

        private static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("LogInfo");
        private string Log4NetConfigPath
        {
            get
            {
                var path = AppDomain.CurrentDomain.BaseDirectory + $"CfgFile/log4net.Config";
                return path;
            }
        }
        public LogHelper() => log4net.Config.XmlConfigurator.Configure(new FileInfo(Log4NetConfigPath));

        public void Info(string info)
        {
            if (loginfo.IsInfoEnabled)
            {
                loginfo.Info(info);
            }
        }

        public void Info(string excptionType, string message, string stackTrace)
        {
            if (loginfo.IsInfoEnabled)
            {
                loginfo.ErrorFormat("{0}:{1}\n{2}", excptionType, message, stackTrace);
            }
        }

        public void Warn(string info)
        {
            if (loginfo.IsWarnEnabled)
            {
                loginfo.Warn(info);
            }
        }

        public void Error(Exception ex)
        {
            if (loginfo.IsErrorEnabled)
            {
                loginfo.Error(ex);
            }
        }

        /// <summary>
        /// 使用建议（⭐⭐⭐⭐⭐）
        /// </summary>
        /// <param name="message"></param>
        public void Error(object message)
        {
            if (loginfo.IsErrorEnabled)
            {
                loginfo.Error(message);
            }
            else
            {
                Log($"打印日志类库出现问题：{loginfo.IsErrorEnabled}" + new FileInfo($"CfgFile/log4net.Config").FullName);
            }
        }

        public void Error(string info, Exception ex)
        {
            if (loginfo.IsErrorEnabled)
            {
                loginfo.Error(info, ex);
            }
        }

        public void Log(string msg)
        {
            try
            {
                string logs = AppDomain.CurrentDomain.BaseDirectory + "Logs\\";
                if (!File.Exists(logs))
                {
                    Directory.CreateDirectory(logs);
                }
                logs += $"{DateTime.Now:yyyyMMdd}.log";
                using (FileStream stream = new FileStream(logs, FileMode.OpenOrCreate))
                {
                    stream.Position = stream.Length;
                    byte[] data = Encoding.UTF8.GetBytes(msg + $" {DateTime.Now.ToString("G")} " + "\r");
                    stream.Write(data, 0, data.Length);
                }
            }
            catch { }
        }
    }
}
